<template>
  <div class="login-container">
    <el-form ref="ruleFormRef" :model="form" class="login-form" :rules="rules">
      <div>
        <h3 class="title">管理后台</h3>
      </div>
      <el-form-item class="form-item" prop="name">
        <el-input v-model="form.name" placeholder="请输入用户名" />
      </el-form-item>

      <el-form-item class="form-item" prop="password">
        <el-input type="password" v-model="form.password" placeholder="请输入登录密码" />
      </el-form-item>
      <el-button :loading="commonStore.loading" type="primary" style="width: 100%; margin-bottom: 30px" @click="handleLogin(ruleFormRef)">登 录</el-button>
    </el-form>
  </div>
</template>
<script lang="ts" setup>
import { ref, reactive } from 'vue'
import type { ElForm } from 'element-plus'
import { OauthLogin } from '@/api/common'
import { useRouter } from 'vue-router'
import { useMenusStore } from '@/stores/menus'
import { useCommonStore } from '@/stores/common'

  const menusStore = useMenusStore()
  const commonStore = useCommonStore()
  type FormInstance = InstanceType<typeof ElForm>
  const ruleFormRef = ref<FormInstance>()
  const router = useRouter()
  const form = reactive({
    name: 'admin',
    password: '123456'
  })
  const rules = reactive({
    name: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
    password: [{ required: true, message: '请输入登录密码', trigger: 'blur' }]
  })
  const handleLogin = (formEl: FormInstance | undefined): void => {
    if (!formEl) return
     formEl.validate((valid) => {
       if (valid) {
        OauthLogin(form).then((res: ServiceResponse<Token>) => {
           if (res.success) {
             localStorage.refreshToken = res.data?.refreshToken
             localStorage.token = res.data?.accessToken
             localStorage.userName =  res.data?.userName ?? ''
             commonStore.userName =  res.data?.userName ?? ''
             menusStore.getMenus().then((res:any) => {
               router.push('/home')
             })
           }
        })
       }
     })
  }
</script>
<style lang="scss" scoped>
  .login-container {
    min-height: 100%;
    width: 100%;
    background-color: #2d3a4b;
    overflow: hidden;
    text-align: center;
    color: #fff;
    .login-form {
      position: relative;
      width: 520px;
      max-width: 100%;
      padding: 160px 35px 0;
      margin: 0 auto;
      overflow: hidden;
    }
  }
</style>
